package com;

import static org.junit.Assert.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.Describable;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class ObtainDirs {
	private static final String __REPLACE__ = "__REPLACE__";
	private static final String BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?address=__REPLACE__,+capital+federal,+argentina&sensor=true";

	@Test
	public void test() throws IOException {
		JsonParser parser = new JsonParser();

		CsvReader readr = new CsvReader("bicicleteros-via-publica.csv");
		CsvWriter writer = new CsvWriter("exp.csv");
		readr.readHeaders();
		while (readr.readRecord()) {
			String id = readr.get("ID");
			String nombre = readr.get("BICICLETEROS/LUGARES");
			String direccion = readr.get("DIRECCION");

			URL url = new URL(BASE_URL.replace(__REPLACE__,
					direccion.replace(" ", "+")));
			InputStreamReader isr = new InputStreamReader(url.openStream());

			JsonElement data = parser.parse(isr);
			if (data.getAsJsonObject().get("results").getAsJsonArray().size() > 0) {
				JsonObject asJsonObject = data.getAsJsonObject().get("results")
						.getAsJsonArray().get(0).getAsJsonObject();
				String lat = asJsonObject.get("geometry").getAsJsonObject()
						.get("location").getAsJsonObject().get("lat")
						.toString();
				String lng = asJsonObject.get("geometry").getAsJsonObject()
						.get("location").getAsJsonObject().get("lng")
						.toString();
				isr.close();

				writer.writeRecord(toArray(id, nombre, direccion, lat, lng));
			}

			writer.flush();
		}

		writer.close();

	}

	public static String[] toArray(String... vars) {
		return vars;
	}
}
